import React, { useState, useEffect } from 'react';
import { Layout, Menu, Avatar, Dropdown, Badge, Input, Button, Breadcrumb, Tooltip, theme, Drawer } from 'antd';
import { Outlet, useNavigate, useLocation, Link } from 'react-router-dom';
import type { MenuProps } from 'antd';
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  DashboardOutlined,
  TeamOutlined,
  SettingOutlined,
  LockOutlined,
  BellOutlined,
  UserOutlined,
  SearchOutlined,
  ProjectOutlined,
  AppstoreOutlined,
  ApartmentOutlined,
  BarChartOutlined,
  FileTextOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  GithubOutlined,
  QuestionCircleOutlined,
  MessageOutlined,
  GlobalOutlined,
} from '@ant-design/icons';
import logo from '@/assets/logo.svg';
import '../styles/mainLayout.less';

const { Header, Sider, Content } = Layout;
const { Search } = Input;

// 定义用户菜单项类型
type UserMenuItem = {
  key: string;
  label?: React.ReactNode;
  icon?: React.ReactNode;
  type?: 'divider';
};

const MainLayout: React.FC = () => {
  const [collapsed, setCollapsed] = useState(false);
  const [currentTime, setCurrentTime] = useState(new Date());
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [isMobile, setIsMobile] = useState(window.innerWidth <= 768);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  
  useEffect(() => {
    const handleResize = () => {
      const mobile = window.innerWidth <= 768;
      setIsMobile(mobile);
      if (!mobile && drawerVisible) {
        setDrawerVisible(false);
      }
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [drawerVisible]);

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    
    // 监听全屏变化
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    
    return () => {
      clearInterval(timer);
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  const handleFullscreenChange = () => {
    setIsFullscreen(!!document.fullscreenElement);
  };

  const toggleFullscreen = () => {
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen().catch(err => {
        console.error(`全屏请求出错: ${err.message}`);
      });
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      }
    }
  };

  // 获取面包屑导航项
  const getBreadcrumbItems = () => {
    const pathSnippets = location.pathname.split('/').filter(i => i);
    const breadcrumbItems = [
      {
        title: <Link to="/dashboard">首页</Link>,
        key: 'dashboard'
      }
    ];
    
    // 简单匹配路由对应的菜单项
    if (pathSnippets.length > 0) {
      let currentMenuItem: any = null;
      
      // 查找一级菜单
      menuItems.forEach(item => {
        if (item.key === pathSnippets[0]) {
          currentMenuItem = item;
        } else if (item.children) {
          // 查找二级菜单
          item.children.forEach((child: any) => {
            if (child.key === pathSnippets[0]) {
              currentMenuItem = child;
              breadcrumbItems.push({
                title: <span>{item.label}</span>,
                key: item.key
              });
            }
          });
        }
      });
      
      if (currentMenuItem) {
        breadcrumbItems.push({
          title: currentMenuItem.label,
          key: currentMenuItem.key
        });
      }
    }
    
    return breadcrumbItems;
  };

  const menuItems = [
    {
      key: 'dashboard',
      icon: <DashboardOutlined />,
      label: '仪表盘',
    },
    {
      key: 'user',
      icon: <TeamOutlined />,
      label: '用户管理',
      children: [
        {
          key: 'user-list',
          label: '用户列表',
        },
        {
          key: 'role-manage',
          label: '角色管理',
        },
      ],
    },
    {
      key: 'system',
      icon: <ApartmentOutlined />,
      label: '系统管理',
      children: [
        {
          key: 'dept',
          label: '部门管理',
        },
        {
          key: 'menu',
          label: '菜单管理',
        },
        {
          key: 'dict',
          label: '字典管理',
        },
      ],
    },
    {
      key: 'monitor',
      icon: <BarChartOutlined />,
      label: '系统监控',
      children: [
        {
          key: 'online',
          label: '在线用户',
        },
        {
          key: 'job',
          label: '定时任务',
        },
        {
          key: 'server',
          label: '服务监控',
        },
      ],
    },
    {
      key: 'tool',
      icon: <AppstoreOutlined />,
      label: '系统工具',
      children: [
        {
          key: 'build',
          label: '表单构建',
        },
        {
          key: 'swagger',
          label: '系统接口',
        },
      ],
    },
    {
      key: 'log',
      icon: <FileTextOutlined />,
      label: '日志管理',
      children: [
        {
          key: 'operlog',
          label: '操作日志',
        },
        {
          key: 'logininfor',
          label: '登录日志',
        },
      ],
    },
  ];

  const userMenuItems: UserMenuItem[] = [
    {
      key: '1',
      label: '个人中心',
      icon: <UserOutlined />,
    },
    {
      key: '2',
      label: '账户设置',
      icon: <SettingOutlined />,
    },
    {
      key: '3',
      type: 'divider',
    },
    {
      key: '4',
      label: '退出登录',
      icon: <LockOutlined />,
    },
  ];

  const handleMenuClick = (e: { key: string }) => {
    navigate(`/${e.key}`);
    if (isMobile) {
      setDrawerVisible(false);
    }
  };

  const renderSideMenu = () => (
    <>
      <div className="logo">
        <div className="logo-icon">
          <img src={logo} alt="Logo" className="logo-image" />
        </div>
        {!collapsed && <div className="logo-text">MiaoMiao Admin</div>}
      </div>
      <div className="menu-container">
        <Menu
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['dashboard']}
          selectedKeys={[location.pathname.split('/')[1] || 'dashboard']}
          items={menuItems}
          onClick={handleMenuClick}
          className="tech-menu"
        />
      </div>
    </>
  );

  return (
    <Layout className="main-layout">
      {!isMobile ? (
        <Sider 
          trigger={null} 
          collapsible 
          collapsed={collapsed}
          className="tech-sider"
          width={260}
        >
          {renderSideMenu()}
        </Sider>
      ) : (
        <Drawer
          placement="left"
          closable={false}
          onClose={() => setDrawerVisible(false)}
          open={drawerVisible}
          width={260}
          bodyStyle={{ padding: 0, background: 'linear-gradient(to bottom, #0a1529, #071630)' }}
          className="mobile-drawer"
        >
          {renderSideMenu()}
        </Drawer>
      )}
      <Layout>
        <Header className="tech-header">
          <div className="header-left">
            <Button
              type="text"
              icon={isMobile ? (drawerVisible ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />) : (collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />)}
              onClick={() => isMobile ? setDrawerVisible(!drawerVisible) : setCollapsed(!collapsed)}
              className="trigger"
            />
            <Breadcrumb items={getBreadcrumbItems()} className="header-breadcrumb" />
          </div>
          
          <div className="header-search">
            <Search 
              placeholder="搜索菜单、页面..." 
              className="search-input"
              prefix={<SearchOutlined />} 
            />
          </div>
          
          <div className="header-right">
            <div className="header-action-items">
              <Tooltip title="切换全屏">
                <Button
                  type="text"
                  icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
                  onClick={toggleFullscreen}
                  className="header-action-btn"
                />
              </Tooltip>
              
              <Button
                type="text"
                icon={<QuestionCircleOutlined />}
                className="header-action-btn hide-on-mobile"
              />
              
              <Button
                type="text"
                icon={<GithubOutlined />}
                className="header-action-btn hide-on-mobile"
              />
              
              <Button
                type="text"
                icon={<GlobalOutlined />}
                className="header-action-btn hide-on-mobile"
              />
              
              <div className="system-time hide-on-mobile">
                {currentTime.toLocaleString()}
              </div>
              
              <Badge count={3} className="notification-badge">
                <Button
                  type="text"
                  icon={<BellOutlined />}
                  className="header-action-btn"
                />
              </Badge>
              
              <Badge count={5} className="message-badge hide-on-mobile">
                <Button
                  type="text"
                  icon={<MessageOutlined />}
                  className="header-action-btn"
                />
              </Badge>
            </div>
            
            <Dropdown menu={{ items: userMenuItems as MenuProps['items'] }} placement="bottomRight" arrow>
              <div className="user-info">
                <Avatar icon={<UserOutlined />} className="user-avatar" />
                <span className="username hide-on-mobile">管理员</span>
              </div>
            </Dropdown>
          </div>
        </Header>
        <Content className="tech-content">
          <div className="content-wrapper">
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

export default MainLayout; 